import React, { Component } from 'react'
import {
    StyleSheet,
    View,
    Text,
    Image,
    ListView,
    ScrollView,
    TouchableOpacity,
    TextInput,
    FlatList,
    TouchableWithoutFeedback
} from 'react-native';

import NavigatorBar from '../../common/NavigationBar'

import { searchTeacher, searchOrg } from '../../api/home';

const Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');

import BackPressComponent from '../../common/BackPressComponent';
export default class SearchComPage extends Component {
    constructor(props) {
        super(props);
        this.params = this.props.navigation.state.params;
        // console.log(this.props.navigation,'-------params')
        this.backPress = new BackPressComponent({ backPress: (e) => this.onBackPress(e) });
        this.state = {
            searchData: [],
            searchText: '',
            page: 1,
            noData: false
        }
    }
    render() {
        return (
            <View>
                <NavigatorBar
                    // title={'e课'}
                    hide={true}
                    style={styles.navigatorBar}
                />
                <View style={styles.searchWrapper}>
                    <View style={styles.searchInput}>
                        <Image style={styles.searchIcon} source={require('../../assets/imgs/icon_search.png')} />
                        <TextInput autoFocus={true} returnKeyType={'search'} placeholder={this.params.type == 'teacher' ? "搜老师" : '搜机构'} onChangeText={(text) => this.handleChangeText(text)} underlineColorAndroid='transparent' style={styles.textInputStyle} placeholderTextColor={'#CCCCCC'}></TextInput>
                    </View>
                    <TouchableOpacity style={styles.filterSort} onPress={() => this.cancle()}>
                        <Text>取消</Text>
                    </TouchableOpacity>
                </View>
                <ScrollView
                    showsVerticalScrollIndicator={false}
                >
                    <FlatList
                        data={this.state.searchData}
                        renderItem={({ item, index }) => this.renderItem({ item, index })}
                        keyExtractor={(item, index) => item.ID || item.USERID}
                    />
                    {this.state.noData && <View style={styles.noDataWrapper}><Text style={styles.noData}>暂无数据</Text></View>}
                </ScrollView>
            </View>
        )
    }

    handleHighlightText(str) {
        if (!str) {
            var data = [];
            this.setState({
                searchData: data
            })
            return
        }
         
        var pre = str.split(this.state.searchText)[0] && str.split(this.state.searchText)[0];
        var last = str.split(this.state.searchText)[1] && str.split(this.state.searchText)[1];
        return <Text>
            <Text>{pre}</Text><Text style={styles.itemHighlightText}>{this.state.searchText}</Text><Text>{last}</Text>
        </Text>;
    }

    renderItem({ item, index }) {
        var itemView = <View key={index}></View>;
        // global.log(item, '1212')
        switch (this.params.type) {
            case 'teacher':
                itemView = <TouchableOpacity style={styles.sectionItemWrapper} key={item.USERID} onPress={() => { this.goToDetail(item) }}>
                    <View><Text style={styles.itemText}>{this.handleHighlightText(item.NAME)}</Text></View>
                </TouchableOpacity>;
                break;
            case 'mechanism':
                itemView = <TouchableOpacity style={styles.sectionItemWrapper} key={item.ID} onPress={() => { this.goToDetail(item) }}>
                    <View><Text style={styles.itemText}>{this.handleHighlightText(item.ORG_NAME
                    )}</Text></View>
                </TouchableOpacity>
                break;
        }
        return (
            itemView
        )
    }
    /**
     * 跳转路由
     * @param {对象数据} item 
     */
    goToDetail(item) {
        global.log(item, 'item');
        var routerName = '';
        var params = {};
        if (this.params.type == 'teacher') {
            routerName = 'TeaIntroduction';
            params = { teacherId: item.USERID }
        }
        else if (this.params.type == 'mechanism') {
            routerName = 'TeaIntroduction';
            params = { orgId: item.ID }
        }

        this.props.navigation.navigate(routerName, {
            ...params
        })
    }

    handleChangeText(text) {
        // if () return;
        if (!text || /^\s+|\s+$/.test(text)) {
            this.setState({
                searchData: [],
                noData: false
            });
            return;
        }
        this.setState({
            searchText: text
        })
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
            // 查询所有数据
            var resData = [];
            this._fetchData(this.params.type, text);
        }, 20)
    }

    _fetchData(type, text) {
        if (type == 'teacher') {
            // TODO: 用户ID
            var teacherData = {
                sendData: {
                    "USERID": global.ECourseConstant.userInfo.uuid,
                    "SORTBYTIME": "1",
                    "NAME": text
                },
                page: this.state.page,
                rows: -1
            };

            searchTeacher(teacherData).then(res => {
                global.log(res, '-----res1111');
                this.setState({
                    searchData: res.LIST,
                    noData: res.LIST.length == 0
                })
            });
        }
        else {
            var mechanismData = {
                sendData: {
                    "EDESC": "0",
                    "ORG_NAME": text
                },
                page: 1,
                rows: 10
            }
            searchOrg(mechanismData).then(res => {
                global.log(res, '-----res2222');
                this.setState({
                    searchData: res.LIST
                })
            });
        }
    }

    componentDidMount() {
        global.log(this.params, 'params')
    }
    onBackPress() {
        // console.log('back', this);
        this.params && this.params.refreshPage && this.params.refreshPage();//返回上一个页面的refreshPage()
    }
    cancle() {
        this.props.navigation.goBack();
        this.onBackPress();
    }

    componentDidMount() {
        this.backPress.componentDidMount();
    }

    componentWillUnmount() {
        this.backPress.componentWillUnmount();
    }
}

const styles = StyleSheet.create({
    // 搜索页面
    appContainer: {
        flex: 1,
        backgroundColor: '#fff'
    },
    searchWrapper: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        backgroundColor: '#fff',
        // backgroundColor: 'red',
        padding: 8
    },
    searchIcon: {
        width: 14,
        height: 14,
        marginLeft: 6
    },
    searchInput: {
        width: width - 80,
        height: 36,
        backgroundColor: '#F7F7F9',
        borderRadius: 27,
        flexDirection: 'row',
        alignItems: 'center',
        marginLeft: 5
    },
    textInputStyle: {
        width: 220,
        height: 36,
        fontSize: 12,
        marginLeft: 5
    },
    filterSort: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        // fontSize: 16
    },
    dropDownIcon: {
        width: 14,
        height: 14
    },
    // 
    resWrapper: {
        paddingLeft: 8,
        paddingRight: 8,
        paddingTop: 4,
        paddingBottom: 4,
        marginTop: 6,
        backgroundColor: '#fff'
    },
    headerTitle: {
        fontSize: 15
    },
    sectionItemWrapper: {
        paddingLeft: 16,
        paddingRight: 8,
        paddingTop: 4,
        paddingBottom: 4,
        backgroundColor: '#fff',
        // backgroundColor: 'red'
    },
    itemText: {
        fontSize: 16
    },
    itemHighlightText: {
        color: '#FF8A00'
    },
    noDataWrapper: {
        marginTop: 120,
        alignItems: 'center'
    },
    noData: {
        color: '#666'
    }
});